package com.robertbruce.astar;

import java.util.ArrayList;
import java.util.List;


public class NodeState<T extends Node<T>> implements Comparable<NodeState<T>>
{
    private T myNode;
    private NodeState<T> myPreviousNode;
    private double myCostSoFar;
    private double myEstimatedCostToTarget = 0.0;

    public NodeState(T theNode, NodeState<T> thePreviousNode, double theCostSoFar, T theTarget) 
    {
        this.myNode = theNode;
        this.myPreviousNode = thePreviousNode;
        this.myCostSoFar = theCostSoFar;
        this.myEstimatedCostToTarget = myCostSoFar + myNode.calculateEstimatedCost(theTarget);
    }

    public List<T> calculatePath()
    {
    	List<T> thePath = new ArrayList<T>();
    	NodeState<T> theCurrentNode = this;
    	
    	while (theCurrentNode != null)
    	{
    		thePath.add(0,theCurrentNode.myNode);
    		theCurrentNode = theCurrentNode.myPreviousNode;
    	}
    	
    	return thePath;
    }
    
	public int compareTo(NodeState<T> theOtherNode)
	{
		double theResult = myEstimatedCostToTarget = theOtherNode.getEstimatedCostToTarget();
		
		if (theResult < 0) 
			return -1;
		else if (theResult > 0)
			return 1;
		else
			return 0;
	}

	@Override
	public String toString()
	{
		StringBuilder sb = new StringBuilder();
		sb.append("[Node (").append(myNode).append(") previousNode (").append(myPreviousNode)
			.append(") cost so Far (").append(myCostSoFar).append(") estimated cost to target (").append(myEstimatedCostToTarget).append(")]");
		return sb.toString();
	}

    public double getEstimatedCostToTarget() { return myEstimatedCostToTarget; }
    public double getTheCostSoFar() { return myCostSoFar; }
    public T getNode() { return myNode; }

}
